import {Component, ViewChild, AfterViewChecked} from "@angular/core";
import {NgForm} from "@angular/forms";
import {LoginInHttpService} from "./shared/service/login-in-http.service";
import {UserModel} from "../shared/model/user.model";
import {Observable} from "rxjs";
import {Router} from "@angular/router";
/**
 * 用户登录组件
 * Created by Administrator on 2016/12/3.
 */
@Component({
    templateUrl: "./login-in.component.html",
    styleUrls: ["./style-source/login-in.component.scss"]
})
export class LoginInComponent implements AfterViewChecked {
    private loginForm: NgForm;
    @ViewChild("loginForm") currForm: NgForm;
    user: UserModel = new UserModel();

    //用户名或密码是否错误的标志
    checkExistResult: boolean = false;

    //验证错误信息存储
    public formErrors = {
        username: '',
        password: ''
    };

    //出错信息
    private validationMessages = {
        username: {
            required: "用户名不能为空",
            minlength: "用户名长度不能少于6位",
            maxlength: "用户名长度不能多于12位"
        },
        password: {
            required: "密码不能为空",
            minlength: "密码长度不能少于6位",
            maxlength: "密码长度不能多于12位"
        }
    };

    constructor(private loginInHttpService: LoginInHttpService, private router: Router) {
    }

    ngAfterViewChecked() {
        this.formChange();
    }

    formChange() {
        if (this.loginForm === this.currForm) {
            return;
        }
        this.loginForm = this.currForm;
        if (this.loginForm) {
            this.loginForm.valueChanges
                .subscribe(data => this.onValueChanged(data));
        }
    }

    onValueChanged(data?: any) {
        this.checkExistResult = false;

        if (!this.loginForm) {
            return;
        }
        const form = this.loginForm.form;

        for (const field in this.formErrors) {
            this.formErrors[field] = '';
            const control = form.get(field);

            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + "  ";
                }
            }
        }
    }

    submit() {
        let observer: Observable<any> = this.loginInHttpService.login(this.user);
        observer.subscribe((result: boolean) => {
                if (result) {
                    this.router.navigate(["index"]);
                } else {
                    this.checkExistResult = true;
                }
            },
            error => {
                alert(error);
            })
    }
}
